<?php

/**
 * This file is part of the People Of Walmart block for Moodle.
 * Copyright (C) 2009-2010 <anonymousmoodler@gmail.com>
 * 
 * The People Of Walmart block is distributed under the terms of the GNU
 * General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version. You should
 * have received a copy of the GNU General Public License along with the People
 * Of Walmart block. If not, see <http://www.gnu.org/licenses/>.
 */

if (empty($_GET['img'])) {
    exit();
}

$img_url = urldecode($_GET['img']);

require_once(dirname(__FILE__).'/../../config.php');

if (empty($CFG->block_peopleofwalmart_cache_thumbnails)) {
    header('Location: '.$img_url);
    exit();
}

if (preg_match('/http:\/\/media\.peopleofwalmart\.com\/wp-content\/uploads\/[a-z0-9\/]+\.jpg/', $img_url) != 1) {
    exit();
}

$img_width = 160;
$img_height = 100;
$thumbnail_quality = 75;

if (isset($CFG->block_peopleofwalmart_thumbnail_quality)) {
    $thumbnail_quality = $CFG->block_peopleofwalmart_thumbnail_quality;
}

$cache_dir = $CFG->dataroot.'/cache/peopleofwalmart/images';
$cache_file = $cache_dir.'/'.sha1($img_url).'.jpg';

header('Content-type: image/jpeg');

if (!file_exists($cache_dir)) {
    mkdir($cache_dir);
}

if (file_exists($cache_file)) {
    $img = imagecreatefromjpeg($cache_file);
    imagejpeg($img, NULL, 100);
} else {
    list($img_full_width, $img_full_height) = getimagesize($img_url);
    $img = imagecreatetruecolor($img_width, $img_height);
    $img_full = imagecreatefromjpeg($img_url);
    imagecopyresampled($img, $img_full, 0, 0, 0, 0, $img_width, $img_height, $img_full_width, $img_full_height);
    imagejpeg($img, $cache_file, $thumbnail_quality);
    imagejpeg($img, NULL, $thumbnail_quality);
}

?>